package com.enation.app.javashop.buyer.api.passport;

import com.enation.app.javashop.core.client.system.SmsClient;
import com.enation.app.javashop.core.distribution.model.dos.DistributionDO;
import com.enation.app.javashop.core.distribution.service.DistributionManager;
import com.enation.app.javashop.core.member.model.dos.ConnectDO;
import com.enation.app.javashop.core.member.model.dos.Member;
import com.enation.app.javashop.core.member.model.dos.MemberCoupon;
import com.enation.app.javashop.core.member.model.dto.MiniproMobileLoginDTO;
import com.enation.app.javashop.core.member.model.enums.ConnectTypeEnum;
import com.enation.app.javashop.core.member.plugin.wechat.WechatConnectLoginPlugin;
import com.enation.app.javashop.core.member.service.ConnectManager;
import com.enation.app.javashop.core.member.service.MemberCouponManager;
import com.enation.app.javashop.core.member.service.MemberManager;
import com.enation.app.javashop.core.promotion.activitymessage.service.ActivityMessageManager;
import com.enation.app.javashop.core.promotion.coupon.model.dos.CouponDO;
import com.enation.app.javashop.core.promotion.coupon.model.dos.CouponTypeEnum;
import com.enation.app.javashop.core.promotion.coupon.service.CouponManager;
import com.enation.app.javashop.core.shop.service.ShopManager;
import com.enation.app.javashop.core.trade.order.service.OrderQueryManager;
import com.enation.app.javashop.framework.cache.Cache;
import com.enation.app.javashop.framework.context.UserContext;
import com.enation.app.javashop.framework.util.DateUtil;
import com.enation.app.javashop.framework.util.HttpUtils;
import com.enation.app.javashop.framework.util.StringUtil;
import com.enation.app.javashop.framework.validation.annotation.Mobile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;
import javax.validation.constraints.Pattern;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author fk
 * @version v2.0
 * @Description: 小程序登录接口
 * @date 2018/11/20 14:56
 * @since v7.0.0
 */
@RestController
@RequestMapping("/passport/mini-program")
@Api(description = "小程序登录api")
@Validated
public class PassportMiniProgramBuyerController {

    @Autowired
    public WechatConnectLoginPlugin wechatConnectLoginPlugin;
    @Autowired
    public ConnectManager connectManager;
    @Autowired
    private MemberManager memberManager;
    @Autowired
    private SmsClient smsClient;
    @Autowired
    private Cache cache;
    @Autowired
    private OrderQueryManager orderQueryManager;
    @Autowired
    private MemberCouponManager memberCouponManager;
    @Autowired
    private ActivityMessageManager activityMessageManager;
    @Autowired
    private CouponManager couponManager;
    @Autowired
    private ShopManager shopManager;
    @Autowired
    private DistributionManager distributionManager;

    // 最新版本
    private static final String CLEAR_VERSION = "C20210105001";
    // 重启版本
    private static final String REBOOT_VERSION = "R20210105001";
    // 版本返回结果
    private static final Map<String, String> VERSION_MAP = new HashMap<>();
    static {
        VERSION_MAP.put("clear_version", CLEAR_VERSION);
        VERSION_MAP.put("reboot_version", REBOOT_VERSION);
    }

    @GetMapping("/get-user-info")
    @ApiOperation(value = "小程序code预登录，获取用户信息")
    public Map getUserInfo(String code, String uuid) {
        return connectManager.getUserInfo(code, uuid);
    }

    @GetMapping("/mobile-login")
    @ApiOperation(value = "小程序手机号登录")
    public Map mobileLogin(@Valid MiniproMobileLoginDTO mobileLoginDTO) {
        return connectManager.mobileLogin(mobileLoginDTO);
    }


    @GetMapping("/only-decrypt")
    @ApiOperation(value = "仅加密数据解密，不自动登陆")
    public Object onlyDecrypt(String code, String encryptedData, String uuid, String iv) {
        return connectManager.onlyDecrypt(code, encryptedData, uuid, iv);
    }

    @GetMapping("/get-version")
    @ApiOperation(value = "查询小程序最新版本信息")
    public Map getVersion() {
        return VERSION_MAP;
    }

    /************************* 历史接口 不能删除 *****************************/


    @GetMapping("/auto-login")
    @ApiOperation(value = "小程序自动登录")
    public Map autoLogin(String code, String uuid) {

        //获取sessionkey和openid或者unionid
        String content = wechatConnectLoginPlugin.miniProgramAutoLogin(code);

        return this.connectManager.miniProgramLogin(content, uuid);
    }


    @GetMapping("/decrypt")
    @ApiOperation(value = "加密数据解密验证，解决成功后自动登陆")
    public Map decrypt(String code, String encryptedData, String uuid, String iv) {

        return connectManager.decrypt(code, encryptedData, uuid, iv);
    }


    @GetMapping("/code-unlimit")
    @ApiOperation(value = "获取微信小程序码")
    public String getWXACodeUnlimit() {

        String accessTocken = wechatConnectLoginPlugin.getWXAccessToken();

        return connectManager.getWXACodeUnlimit(accessTocken);
    }

    @ApiOperation(value = "小程序注册绑定")
    @PostMapping("/register-bind/{uuid}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uuid", value = "唯一标识", required = true, dataType = "String", paramType = "path"),
            @ApiImplicitParam(name = "nick_name", value = "昵称", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "face", value = "头像", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "sex", value = "性别", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "mobile", value = "手机号码", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String", paramType = "query")

    })
    public Map binder(@PathVariable("uuid") String uuid, @Length(max = 20, message = "昵称超过长度限制") @ApiIgnore String nickName, String face, Integer sex, @Mobile String mobile, @Pattern(regexp = "[a-fA-F0-9]{32}", message = "密码格式不正确") String password) {
        //执行注册
        Member member = new Member();
        member.setUname("m_" + mobile);
        member.setMobile(mobile);
        member.setPassword(password);
        member.setNickname(nickName);
        member.setFace(face);
        member.setSex(sex);
        memberManager.register(member);
        //执行绑定账号
        Map map = connectManager.mobileBind(mobile, uuid);
        return map;
    }


    @GetMapping("/get-access-token")
    @ApiOperation(value = "获取小程序accessToken")
    public String getAccessToken() {
        return wechatConnectLoginPlugin.getWXAccessToken();
    }


    @GetMapping("/getliveinfo")
    @ApiOperation(value = "获取直播列表")
    public String getliveinfo(Integer start, Integer limit) {
        String url = "https://api.weixin.qq.com/wxa/business/getliveinfo?access_token=" + wechatConnectLoginPlugin.getWXAccessToken();
        Map<String, Object> params = new HashMap<>();
        params.put("start", start);
        params.put("limit", limit);
        return HttpUtils.doPostWithJson(url, params);
    }

    @GetMapping("/home_pop_up")
    @ApiOperation(value = "首页营销弹窗")
    public Integer homePopUp(String openId,String city) {
        // 1.0 未注册的新用户 标识 1 已注册未下单并且没有新人券 标识 2 老用户
        Integer flag = -1;
        if(StringUtil.isEmpty(city) || StringUtil.isEmpty(openId)){
            flag= -1 ;
        }else{
            // 根据用户所在城市定位店铺优惠券
            Integer sellerId = shopManager.getShopByCity(city);
            if(sellerId!=null && sellerId!=0){
                // 查询是否注册
                ConnectDO connectDO = connectManager.getConnect(openId, ConnectTypeEnum.WECHAT.value());
                if(StringUtils.isEmpty(connectDO)){

                    // 4.1.1 查询该店铺有没有新人券
                    List<CouponDO> couponList = couponManager.getList(sellerId,CouponTypeEnum.NEW_REG.value());
                    if(CollectionUtils.isEmpty(couponList)){
                        flag = -1;
                    }else {
                        // 查看已被领取的数据量是否和发放量相同
                        for (CouponDO couponDO : couponList) {
                            if(couponDO.getReceivedNum() < couponDO.getCreateNum()){
                                // 根据优惠券使用时间类型 区分
                                if("FIX".equals(couponDO.getUseTimeType()) && couponDO.getUseEndTime() > DateUtil.getDateline()){
                                    // 3.1 判断当前人进来是不是未注册的新用户
                                    flag = 0;
                                    break;
                                }else if("PERIOD".equals(couponDO.getUseTimeType())){
                                    // 3.1 判断当前人进来是不是未注册的新用户
                                    flag = 0;
                                    break;
                                }
                            }
                        }
                    }
                }else{
                    // 查询当前人是否是通过推广领券注册的
                    DistributionDO distributionDO = distributionManager.getDistributorByMemberId(connectDO.getMemberId());
                    Integer visitChannel = -1 ;
                    if(distributionDO != null ){
                        visitChannel = distributionDO.getVisitChannel();
                    }

                    // 4.0 查询是否下过单 订单状态为已付款
                    Integer orderNum = orderQueryManager.getOrderNumberByMemberId(connectDO.getMemberId(),sellerId) ;
                    if(orderNum != null && orderNum != 0){
                        // 查看有没有订阅该店铺里面的最新活动
                        Integer subscribeActivity = activityMessageManager.getSubscribeActivity(connectDO.getMemberId(), city);
                        if(subscribeActivity != null && subscribeActivity != 0){
                            flag = -1;
                        } else {
                            flag = 2;
                        }
                    }else{
                        // 切换城市 查切换城市的店铺有没有新人券
                        List<CouponDO> couponList = couponManager.getList(sellerId,CouponTypeEnum.NEW_REG.value());
                        if(CollectionUtils.isEmpty(couponList)){
                         return  flag;
                        }
                        // 查询这个店铺里面的新人卷发放的数据 是否大于 领取的数量
                        Integer couponId = -1;
                        for (CouponDO couponDO : couponList) {
                            if(couponDO.getReceivedNum() < couponDO.getCreateNum()){
                                // 根据优惠券使用时间类型 区分
                                if("FIX".equals(couponDO.getUseTimeType()) && couponDO.getUseEndTime() > DateUtil.getDateline()){
                                    couponId = couponDO.getCouponId();
                                    break;
                                }else if("PERIOD".equals(couponDO.getUseTimeType())){
                                    couponId = couponDO.getCouponId();
                                    break;
                                }
                            }
                        }
                        // 当前地区的店铺新人券被领完了
                        if(couponId == -1){
                          return  flag;
                        }

                        if(visitChannel == null || visitChannel != 6){
                            // 查看有没有领过这个地区店铺的新人券
                            Integer couponNum = memberCouponManager.getCouponNum(connectDO.getMemberId(), sellerId,CouponTypeEnum.NEW_REG.value());
                            if(couponNum == null || couponNum == 0){
                                return  0 ;
                            }
                        }
                        // 4.1.2 查询当前人是否领过新人券(店铺新人券) , 查询有没有领过拉新券 .并且新人券和拉新券 未过期
                        String[] couponType = {CouponTypeEnum.NEW_REG.value(),CouponTypeEnum.PULL_NEW.value()};
                        MemberCoupon newMemberCoupon = memberCouponManager.getNewCoupon(connectDO.getMemberId(), sellerId,couponType);
                        // 5.0 (新人券 或 拉新券 已失效  )
                        if( StringUtils.isEmpty(newMemberCoupon)){
                            // 4.1.1 查询该店铺有没有首单券
                            List<CouponDO> firstcCuponList = couponManager.getList(sellerId,CouponTypeEnum.FIRST_ORDER.value());
                            // 查询这个店铺里面的首单券发放的数据 是否大于 领取的数量
                            Integer firstCouponId = -1;
                            for (CouponDO couponDO : firstcCuponList) {
                                if(couponDO.getReceivedNum() < couponDO.getCreateNum()){
                                    firstCouponId = couponDO.getCouponId();
                                    break;
                                }
                            }
                            //  当前地区的店铺首单券被领完了
                            if(firstCouponId == -1){
                                flag = -1;
                            }else {
                                flag = 1;
                                // 4.2.2 查询当前人是否领过首单券(店铺首单券)
                                Integer firstCouponNum = memberCouponManager.getCouponNum(connectDO.getMemberId(),sellerId,CouponTypeEnum.FIRST_ORDER.value());
                                //  领取过首单券 就是老用户
                                if(firstCouponNum != null && firstCouponNum !=0){
                                    // 查看有没有订阅该店铺里面的最新活动
                                    Integer subscribeActivity = activityMessageManager.getSubscribeActivity(connectDO.getMemberId(), city);
                                    if(subscribeActivity != null && subscribeActivity != 0){
                                        flag = -1;
                                    } else {
                                        flag = 2;
                                    }
                                }
                            }
                        }else {
                            // 下过单,并且领过新人券 而且新人券没有失效 是老用户
                            // 查看有没有订阅该店铺里面的最新活动
                            Integer subscribeActivity = activityMessageManager.getSubscribeActivity(connectDO.getMemberId(), city);
                            if(subscribeActivity != null && subscribeActivity != 0){
                                flag = -1;
                            } else {
                                flag = 2;
                            }
                        }
                    }
                }
            }else {
                flag = -1;
            }
        }
        return flag;
    }

    @GetMapping("/get_official_account")
    @ApiOperation(value = "查看是否已经关注公众号")
    public boolean getOfficialAccount() {
      return connectManager.getOfficialAccount();
    }

}
